# 多线程版本
import datetime
from concurrent.futures import as_completed
from concurrent.futures import ThreadPoolExecutor
# from concurrent.futures import ProcessPoolExecutor

from pprint import pprint
import numpy

# 运行函数计数器
countA: int = 0
# 设置目标数值
R1: float = 13714714

# 设置搜索范围,价格
A_range = numpy.arange(0, 3.50, 0.001)  # armCpu价格
B_range = numpy.arange(0, 0.001, 0.001)  # x86Cpu价格
C_range = numpy.arange(0, 4.00, 0.001)  # ARM 内存价格
D_range = numpy.arange(0, 0.001, 0.001)  # X86 内存价格
E_range = numpy.arange(0, 0.09, 0.001)  # 存储价格
# 设置硬件数量
A: int = 16040  # armCpu
B: int = 0  # x86Cpu
C: float = 60589.33  # ARM 内存
D: int = 0  # X86 内存
E: float = 3564769.28  # 存储
# 结果list
res_list: list = []


def r1_r2_subtraction(r2: float) -> float:
    global R1
    return R1 - r2


def calculate_r2(a: float, b: float, c: float, d: float, e: float) -> dict:
    global A, B, C, D, E, countA
    res: float = (A * a + B * b + C * c + D * d + E * e) * 365
    dictA: dict = {
        'AP': a,
        'BP': b,
        'CP': c,
        'DP': d,
        'EP': e,
        'res': res,  # 本次计算的总值
        'abs': float(abs(r1_r2_subtraction(res)))  # R1-R2后的绝对值
    }
    # countA += 1
    # print(countA, end='\r')
    print(dictA, end='\r')
    return dictA


def comput_for(a):
    # global countA
    # countA += 1
    # print(countA, end='\r')
    _list: list = []
    for b in B_range:
        for c in C_range:
            for d in D_range:
                for e in E_range:
                    _a = calculate_r2(a, b, c, d, e)
                    _list.append(_a)
    return _list


def main():
    start_time = datetime.datetime.now()
    with ThreadPoolExecutor(max_workers=16) as pool:
        task_list = [pool.submit(comput_for, a) for a in A_range]
        # wait(task_list, return_when=ALL_COMPLETED)
        # print(task_list)
        result_list = [future.result() for future in as_completed(task_list)]
        pprint(result_list)
        print(len(result_list))
        sum_list: list = []
        for _i in result_list:
            sum_list += _i
        min_dict = min(sum_list, key=lambda x: x["abs"])
        max_dict = max(sum_list, key=lambda x: x["res"])
        print('min,abs>>>>>', end='')
        pprint(min_dict)
        print('max,res>>>>>', end='')
        pprint(max_dict)
    end_time = datetime.datetime.now()
    # print(type(min_dict))
    with open('result.txt', 'w') as res:
        res.write(str(start_time) + '\n')
        res.write(min_dict + '\n')
        res.write(max_dict + '\n')
        res.write(str(end_time) + '\n')


if __name__ == "__main__":
    main()
